package com.bigflexlib.etc.tree
{

	import mx.collections.ArrayList;


	/**
	 * 
	 * A special implementation of IList that intercepts mutators and disallows
	 * invalid actions according to the tree semantics ( and the current tree config ).
	 * 
	 * @author aldo.bucchi@gmail.com
	 * 
	 */
	public class TreeChildrenList extends ArrayList
	{

		
		private var node:TreeNode;


		// flex bug? this is not declared in the superclass
		[Bindable("collectionChange")]
		override public function get length():int
		{
			return super.length;			
		}




		public function TreeChildrenList( node:TreeNode )
		{
			this.node = node;
		}




		//////////////////////////////////////////////////////
		// adding items
		//////////////////////////////////////////////////////



		/**
		 * 
		 * An item can be added if it is not an ancestor and the config allows it
		 * 
		 * @param item
		 * @return 
		 * 
		 */
		public function canAddItem( item:Object ):Boolean
		{
			var tn:TreeNode = item as TreeNode;

			if ( tn == null )
			{
				return false;
			}
			
			if ( node == tn )				// cannot add self
			{
				return false;
			}

			if ( node.hasAncestor( tn ) )	// cannot add an ancestor
			{
				return false;
			}
			
			if ( node.config != null )
				return node.config.canAddChild( node, tn );
				
			return true;		
		}

		
		
		
		
		

		override public function addItemAt( item:Object, index:int ):void
		{


			if ( ! canAddItem( item ) )
			{
				return;
			}
			
			
			var child:TreeNode = item as TreeNode;
			
			

			if ( child.parent != this.node )
			{
				if ( child.parent != null )
				{
					child.parent.children.removeItem( child );					
				}
				
				child.setParent( this.node );
							
			}			
			
			

			super.addItemAt( child, index );
			
		}
		
		



		
		
		override public function setItemAt( item:Object, index:int ):Object
		{
			// TODO ( intercept )
			return super.setItemAt( item, index );
		}
		
		
		
				
		
		
	}
	
}